package com.ocm.commerceinteraction.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.JsonSyntaxException;
import com.ocm.commerceinteraction.GlobalApplication;
import com.ocm.commerceinteraction.R;
import com.ocm.commerceinteraction.config.RequestAddr;
import com.ocm.commerceinteraction.model.BaseModel;
import com.ocm.commerceinteraction.model.FriendsList;
import com.ocm.commerceinteraction.model.GroupDetailModel;
import com.ocm.commerceinteraction.model.GroupMemberBean;
import com.ocm.commerceinteraction.model.UserModel;
import com.ocm.commerceinteraction.ui.adapter.XTContactAdapter;
import com.ocm.commerceinteraction.util.MethedUtil;
import com.ocm.commerceinteraction.util.helper.LogHelper;
import com.ocm.commerceinteraction.util.http.AjaxCallBack;
import com.ocm.commerceinteraction.util.view.sortlist.CharacterParser;
import com.ocm.commerceinteraction.util.view.sortlist.PinyinComparator;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import easeui.domain.EaseUser;
import easeui.widget.EaseContactList;
import easeui.widget.EaseSidebar;

/**
 * Created by Curry on 2016-5-7.
 */
@EActivity(R.layout.activity_select_user)
public class UserListActivity extends BaseActivity {
    @ViewById(R.id.content_container)
    FrameLayout contentContainer;

    @ViewById(R.id.contact_list)
    EaseContactList easeContactList;
    @ViewById(R.id.search_clear)
    ImageButton clearSearch;
    @ViewById(R.id.query)
    EditText query;
    @ViewById(R.id.list)
    ListView listView;

    @ViewById(R.id.right_text_btn)
    TextView rightBtn;

    @ViewById(R.id.sidebar)
    EaseSidebar sidebar;
    @ViewById(R.id.toptitle_title)
    TextView topTitle;

    XTContactAdapter xtContactAdapter;
    @Extra("userListEntity")
    List<GroupDetailModel.DataEntity.UserListEntity> userListEntity;


    @AfterViews
    void initView() {
        topTitle.setText("群成员列表");
        rightBtn.setVisibility(View.GONE);
        characterParser = CharacterParser.getInstance();
//        loadData();
        dealData();
        query.addTextChangedListener(new TextWatcher() {
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                filter(s);
                if (s.length() > 0) {
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    clearSearch.setVisibility(View.INVISIBLE);

                }
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void afterTextChanged(Editable s) {
            }
        });
        clearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();
            }
        });

        listView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 隐藏软键盘
                hideSoftKeyboard();
                return false;
            }
        });
    }

    public void filter(CharSequence str) {
        xtContactAdapter.getFilter().filter(str);
    }


    //处理数据
    BaseModel baseModel;
    List<UserModel> userModelList = new ArrayList<>();

    private void dealData() {
        userModelList.clear();
        String[] date = new String[userListEntity.size()];
        for (int i = 0; i < userListEntity.size(); i++) {
            date[i] = userListEntity.get(i).getNick();
        }
        SourceDateList = filledData(date);
        // 根据a-z进行排序源数据
        Collections.sort(SourceDateList, pinyinComparator);
        userlist.clear();
        LogHelper.i("size:" + SourceDateList.size());
        for (int i = 0; i < SourceDateList.size(); i++) {
            for (int j = 0; j < userListEntity.size(); j++) {
                LogHelper.i("getNick:"+userListEntity.get(j).getNick());
                LogHelper.i("getName:"+SourceDateList.get(i).getName());
                if (userListEntity.get(j).getNick() == null) {
                    continue;
                }
                if (userListEntity.get(j).getNick().equals(SourceDateList.get(i).getName())) {
                    EaseUser easeUser = new EaseUser(userListEntity.get(j).getNick());
                    easeUser.setInitialLetter(SourceDateList.get(i).getSortLetters());
                    easeUser.setSelect(false);
                    easeUser.setEid(userListEntity.get(j).getUser_uniq_id());
                    easeUser.setAvatar(userListEntity.get(j).getIcon());
                    easeUser.setUsername(userListEntity.get(j).getNick());
                    userlist.add(easeUser);
                    break;
                }
            }
        }
        xtContactAdapter = new XTContactAdapter(this, 0, userlist, 0);
        listView.setAdapter(xtContactAdapter);
    }

    @ItemClick(R.id.list)
    void userItemClick(int position) {
        Fragment userDetailFragment = new UserDetailFragment_();
        //add by Eric
        Bundle bundle = new Bundle();
        bundle.putString("userUniqId", userListEntity.get(position).getUser_uniq_id());
//        bundle.putInt("from", MethedUtil.FROM_GROUP );
//        bundle.putString("groupUniqId",groupUniqIds);
        userDetailFragment.setArguments(bundle);

//       getSupportFragmentManager()
//                .beginTransaction()
//                .replace(R.id.content_none_bottom, userDetailFragment).addToBackStack(null).commit();
    }

    public static int RES_FRILIST = 001;

    @Override
    @Click(R.id.right_text_btn)
    void Click(View view) {
        switch (view.getId()) {
            case R.id.right_text_btn:
                String friendList = "";
                for (int i = 0; i < userlist.size(); i++) {
                    if (userlist.get(i).isSelect()) {
                        friendList += "," + userlist.get(i).getEid();
                    }
                }
                Intent intent = new Intent();
                intent.putExtra("friendList", friendList);
                setResult(RES_FRILIST, intent);
                finish();
                break;
        }
    }

    protected InputMethodManager inputMethodManager;

    protected void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null){
                if (inputMethodManager != null) {
                    inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
    }


    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;
    private List<GroupMemberBean> SourceDateList;
    private List<EaseUser> userlist = new ArrayList<>();
    /**
     * 根据拼音来排列ListView里面的数据类
     */
    private PinyinComparator pinyinComparator;

    /**
     * 为ListView填充数据
     *
     * @param date
     * @return
     */
    private List<GroupMemberBean> filledData(String[] date) {
        List<GroupMemberBean> mSortList = new ArrayList<GroupMemberBean>();

        for (int i = 0; i < date.length; i++) {
            GroupMemberBean sortModel = new GroupMemberBean();
            sortModel.setName(date[i]);
            // 汉字转换成拼音
            String pinyin = characterParser.getSelling(date[i]);
            if (pinyin.equals("")) {
                pinyin = "#";
            }
            String sortString = pinyin.substring(0, 1).toUpperCase();

            // 正则表达式，判断首字母是否是英文字母
            if (sortString.matches("[A-Z]")) {
                sortModel.setSortLetters(sortString.toUpperCase());
            } else {
                sortModel.setSortLetters("#");
            }

            mSortList.add(sortModel);
        }
        return mSortList;

    }
}
